package com.unitymarvel.harmonyos.projects.findme;

import com.unitymarvel.harmonyos.projects.findme.common.Tools;
import com.unitymarvel.harmonyos.projects.findme.slice.DeviceListAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.utils.zson.ZSONObject;

import java.io.*;
import java.net.Socket;
///////////////////////////////////////////////////
// 项目的详细实现过程：https://ke.qq.com/course/3677276?tuin=a22a65ce
// 关注微信公众号和B站，获取更多鸿蒙学习资源
// 微信公众号：极客起源
// B站：https://space.bilibili.com/477001733
//
// 作者:李宁（蒙娜丽宁）
//
// 版本: 1.0
// Copyright (C), 2001-2022, 李宁
// 程序被版权法保护
//
///////////////////////////////////////////////////
public class DeviceListAbility extends Ability implements IAbilityContinuation {
    public static Socket clientSocket;
    private static Thread thread;
    public static String serverRandomChar = "";   // 服务端产生的随机字符
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(DeviceListAbilitySlice.class.getName());
    }

    @Override
    public boolean onStartContinuation() {
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam("ip", Tools.getLocalIP(this));
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        String ip = String.valueOf(intentParams.getParam("ip"));
        Tools.showTip(this, ip);
        if(thread== null) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        clientSocket = new Socket(ip, 8888);

                        InputStream is = clientSocket.getInputStream();
                        OutputStream os = clientSocket.getOutputStream();
                        BufferedWriter bw;
                        for(;;) {
                            // 读取服务端返回的消息
                            BufferedReader br = new BufferedReader(new InputStreamReader(is));
                            final String cmd = br.readLine();
                            if("widget_count:".equals(cmd)) {
                                bw = new BufferedWriter(new OutputStreamWriter(os));
                                // 向服务端传输1*2卡片的数量
                                bw.write("widget_count:" + MainAbility.gameWidgetFormIds.size() + "\n");
                                bw.flush();
                            } else if(cmd.startsWith("random_char:")) {
                                // 接收服务端传过来的随机字符
                                serverRandomChar = cmd.substring("random_char:".length());

                            } else if(cmd.startsWith("random_chars:")) {
                                // 客户端更新
                                MainAbility.startFlag = true;
                                final String randomChars = cmd.substring("random_chars:".length());
                                int i = 0;
                                if(randomChars.length() == MainAbility.gameWidgetFormIds.size() * 2) {
                                    for(MainAbility.GameWidgetData gameWidgetData: MainAbility.gameWidgetFormIds.values()) {
                                        gameWidgetData.leftValue = String.valueOf(randomChars.charAt(i));
                                        gameWidgetData.rightValue = String.valueOf(randomChars.charAt(i + 1));
                                        i++;
                                        String[] colors = Tools.getTwoRandomHexColor();
                                        gameWidgetData.leftBackgroundColor = colors[0];
                                        gameWidgetData.leftColor = colors[1];

                                        colors = Tools.getTwoRandomHexColor();
                                        gameWidgetData.rightBackgroundColor = colors[0];
                                        gameWidgetData.rightColor = colors[1];
                                    }

                                    for(long gameWidgetFormId: MainAbility.gameWidgetFormIds.keySet()) {
                                        MainAbility.GameWidgetData gameWidgetData = MainAbility.gameWidgetFormIds.get(gameWidgetFormId);
                                        ZSONObject zsonObject = new ZSONObject();
                                        zsonObject.put("leftValue", gameWidgetData.leftValue);
                                        zsonObject.put("rightValue", gameWidgetData.rightValue);

                                        zsonObject.put("backgroundColor1", gameWidgetData.leftBackgroundColor);
                                        zsonObject.put("backgroundColor2", gameWidgetData.rightBackgroundColor);

                                        zsonObject.put("color1", gameWidgetData.leftColor);
                                        zsonObject.put("color2", gameWidgetData.rightValue);

                                        FormBindingData formBindingData = new FormBindingData(zsonObject);

                                        updateForm(gameWidgetFormId, formBindingData);
                                    }

                                }

                            }
                        }



                    }catch (Exception e) {

                    }
                }
            });
            thread.start();
        }
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {

    }
}
